<?php
// +----------------------------------------------------------------------
// | ZengCMS [ 火火 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://zengcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 火火 <zengcms@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | Token接口，获取令牌，相当于登录
// +----------------------------------------------------------------------
namespace app\api\controller\v1;

use think\facade\Cache;
use app\api\lib\JwtAuth;
use app\api\service\JwtToken;
use app\api\service\AppJwtToken;
use app\api\validate\AppTokenGet;
use app\api\controller\BaseController;
use app\api\lib\exception\MissException;

class Token extends BaseController
{
    /**
     * 获取cms登录token令牌
     * @url /token/app
     * @Http POST
     * @param  string $ac [description]
     * @param  string $se [description]
     * @return [type]     [description]
     */
    public function getAppToken($ac = '', $se = '')
    {
        (new AppTokenGet())->goCheck();
        $token = (new AppJwtToken())->get($ac, $se);
        return $this->return_data(['token' => $token]);
    }
    /**
     * 检查token是否有效
     * @url /token/verify
     * @Http POST
     * @param  string $token [description]
     * @return [type]        [description]
     */
    public function verifyToken($token = '')
    {
        $data = JwtToken::verifyToken($token);
        return $this->return_data($data);
    }
    /**
     * 刷新token
     * @url /token/refresh_token
     * @Http POST
     * @param [type] $refresh_token
     * @return void
     */
    public function refreshToken($refresh_token)
    {
        $oldtoken = request()->post('token');
        $jwt = JwtAuth::getInstance()->setToken($oldtoken)->decode();
        $uid = $jwt->getDataStringByKey('uid');
        $_oldtoken = Cache::store('file')->get('JwtToken_'.$uid);
        if($oldtoken != $_oldtoken){
            throw new MissException([
                'message'=>'异常'
            ]);
        } 
        $refresh_token = $jwt->getData();
        $_jwt = JwtAuth::getInstance()->setDataFromString($refresh_token)->encode();
        $token = $_jwt->getToken();
        // 设置token缓存(白名单，重复获取token时之前的token就失效)
        Cache::store('file')->set('JwtToken_'.$uid,$token);
        return $this->return_data(['token' => $token]);
    }
}
